import os
import sys
import shutil
import json
import queue


from utils.common_utils import *
from base.defines import Attribute
from base.irgen import IRGen

def whole_ir_build(context=None, build_graph=None):
    
    if not build_graph:
        return
    
    reversed_graph = build_graph.get_reversed_graph_with_degree()
    build_queue = queue.Queue()
    
    ready_nodes = [node for node, in_degree in reversed_graph.in_degree_iter() if in_degree == 0]
    
    for node in ready_nodes:
        build_queue.put_nowait(node)
    
    first_level_nodes = []
    
    while(not build_queue.empty()):
        work_node = build_queue.get_nowait()
        if not build_graph.read_attribute(1):
            successors = reversed_graph.successors(work_node)
            for successor in successors:
                degree_dict = reversed_graph.node.get(successor)
                if not degree_dict:
                    first_level_nodes.append(successor)
                degree_dict[successor] -= 1
                
                if degree_dict[successor] == 0:
                    first_level_nodes.append(successor)
    
    for work_node in first_level_nodes:
        ori_command = build_graph.read_attribute(work_node, Attribute.COMMAND)
        parser = build_graph.read_attribute(work_node, Attribute.PARSER)(command=ori_command, context=context)
        compiler,options = parser.parse_gcc_command()
        build_command = parser.get_maple_compile_command()
        for command in build_command:
            ret, _, _ = run_notty_command(command=command)

if __name__ == "__main__":
    
    irgen = IRGen()
    irgen.run()
    
    